import { State } from "framework/FSM/AState";
import { ActionArgHelper } from "../../../ActionManager/ActionArgHelper";
import { EntityHelper } from "utils/entity/EntityHelper";
import { ActionUtils } from "../utils/ActionUtil";
import { PositionHelper } from "utils/position/PositionHelper";
 

/**
援助建设
 */ 
export class HelpBuildTask<T extends IStateArg<Creep>>  extends State<T>
{

    //
    public  getActions(arg:T):Action[]
    {
        const memory = arg.entity.getNodeMemory();
        if(!memory.taskid)
        {
            return [];
        }
        const task =arg.task as ITask<ICreepTaskData<"helpBuild">>;
        if(!task)
        {
            // 查找不到任务
            return []
        }
        const creep = arg.entity;
        if(creep.room.name != task.data.room && task.data.room  )
        {
            //if(!creep.memory._moveCache?.path && !Game.rooms[task.data.room] )
            {
                return [ActionArgHelper.actionMoveto(creep,{pos:PositionHelper.roomCenter(task.data.room),range:10,}, {IsEludeHostile:true,IsRealtime:true,portal:task.data.portal})]
            }
            //return []
        }
        if(!task.data.arg.Objects || task.data.arg.Objects.length==0)
        {
            return []
        }
        
        // 建造任务
        // 1.能量不足。则取取能量
        // 1.a sourceid 存在。且能量足够 => withdraw
        // 1.b !(sourceid 存在。且能量足够) => 更新sourceId
      
 
        if(creep.store.getUsedCapacity(RESOURCE_ENERGY)==0)
        {
            creep.memory.state = 0;

        }
        else  if(creep.store.getFreeCapacity(RESOURCE_ENERGY)==0)
        {
            creep.memory.state = 1;
        }
        if(creep.memory.state)
        {
            const towers = creep.room.getStructures(STRUCTURE_TOWER).filter(e=>e.store.getUsedCapacity(RESOURCE_ENERGY)==0);
            if(towers.length)
            {
                return [ActionArgHelper.actionTransfer(creep,towers[0])]
            }

            if(!creep.memory.targetId)
            {
                // const neartarget = _.min(task.data.arg.Objects,e=>creep.pos.distance(e) );
                creep.memory.targetId =task.data.arg.Objects[0].id;
            }
            const siteobject = Game.getObjectById(creep.memory.targetId as Id<ConstructionSite>) ;
            if(!siteobject)
            {
                creep.memory.targetId=undefined;
                return [ ]
            }
            return [ActionArgHelper.actionBuild(creep,siteobject)]
        }
        else
        {
            return  ActionUtils.getNormalAction(creep,Game.rooms[task.data.room?task.data.room:creep.room.name])
        }
        // 能量足够。则进行工作
        /**
         * targetId 不存在 -> targetId
         * targetId  存在 -> 进行工作
        */
       // return [ ];
    }
}
